<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>数字时钟</title>
  <style>
    body {
      display: flex; justify-content: center; align-items: center;
      height: 100vh; margin: 0; background: #222; color: #0f0;
      font-family: 'Courier New', monospace; font-size: 4rem;
    }
    #clock { text-align: center; }
    #formatToggle {
      display: block; margin-top: 1rem;
      padding: 0.5rem 1rem; font-size: 1rem;
      background: #0f0; color: #222; border: none; cursor: pointer;
    }
  </style>
</head>
<body>
  <div id="clock">
    <div id="time">00:00:00</div>
    <button id="formatToggle">切换12/24小时制</button>
  </div>
  <script>
    let is24Hour = true;
    const timeEl = document.getElementById('time');
    const btn = document.getElementById('formatToggle');
    btn.addEventListener('click', () => is24Hour = !is24Hour);

    function updateClock() {
      const now = new Date();
      let h = now.getHours();
      const m = now.getMinutes();
      const s = now.getSeconds();
      let ampm = '';

      if (!is24Hour) {
        ampm = h >= 12 ? ' PM' : ' AM';
        h = h % 12 || 12;
      }

      const pad = n => String(n).padStart(2, '0');
      timeEl.textContent = `${pad(h)}:${pad(m)}:${pad(s)}${ampm}`;
    }

    setInterval(updateClock, 1000);
    updateClock();
  </script>
</body>
</html>
